package core

import (
	"database/sql"
	"fmt"

	_ "github.com/coreos/bbolt"
	_ "github.com/go-sql-driver/mysql"
	"cn.pinming/gencode/core/api"
	"strings"
	"cn.pinming/gencode/core/logs"
)

var (
	DB *sql.DB
)

// 初始化数据库连接池
func initDatabase() {
	dbConfig := GetDatasouce()
	user := dbConfig.Username
	password := dbConfig.Password
	host := dbConfig.Host
	_db := dbConfig.Database
	port := dbConfig.Port
	//root:123@tcp(localhost:3306)/pm-suite
	//user:password@tcp(127.0.0.1:3306)/hello
	dblink := FormatDburl(user, password, host, port, _db)
	DB, _ = sql.Open("mysql", dblink)
	Logger().Debugf("初始化数据库连接地址：%s", dblink)
	go testDb(dblink)
}

func FormatDburl(user string, password string, host string, port int, database string) string {
	dblink := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=%s&loc=%v&parseTime=true",
		user, password, host, port, database, "utf8", "Asia%2FShanghai")
	return dblink
}

func testDb(url string) {
	err := DB.Ping()
	if err != nil {
		Logger().Errorf("数据库连接地址无效，url:%s,msg:%v", url, err)
		panic(err)
	}
	Logger().Debugf("初始化数据库连接地址 PING成功，url:%s", url)
}

func closeDatabase() {
	Logger().Debug("准备关闭数据库连接池")
	if DB != nil {
		err := DB.Close()
		if err != nil {
			Logger().Errorf("数据库连接池关闭失败:%v", err)
		}
	}
}

/**
 @params pageIndex 分页导航，从1开始计数
 */
func  GetPaged(tableName , fields, whereClause,orderBy string,limit int, pageIndex int,dest ...interface{})  api.PagedTableList {
	pagedList := api.PagedTableList{}
	pagedList.Code = SUCCESS
	pagedList.Msg = SUCCESS_MSG
	pagedList.Data = make([]interface{}, 0)
	if len(tableName) > 0{
		pagedList.Msg="数据表无效"
		pagedList.Code=ERROR
		return pagedList;
	}
	if(len(fields)==0){
		fields="*"
	}
	sqlClause:=fmt.Sprintf(" from %s",tableName)
	whereClause=strings.TrimSpace(whereClause)
	if(len(whereClause)>0){
		if(strings.Index(strings.ToUpper(whereClause),"where ")==0){
			sqlClause=fmt.Sprintf(" %s %s",sqlClause,whereClause)
		}else{
			sqlClause=fmt.Sprintf(" %s where %s",sqlClause,whereClause)
		}
	}
	countClause:="select count(*) "+sqlClause;
	sqlClause= fmt.Sprintf("select %s %s",fields,sqlClause)
	if limit < 1 {
		limit = 15
	}
	if limit > 0 {
		if pageIndex < 1 {
			pageIndex=1
			sqlClause = fmt.Sprintf("%s limit %d", sqlClause, limit)
		}else{
			skip := limit * (pageIndex - 1)
			sqlClause = fmt.Sprintf("%s limit %d,%d", sqlClause, skip, limit)
		}
	}

	rows, err := DB.Query(countClause)
	logs.Debugf("SQL语句:%s", sqlClause)
	if err != nil {
		logs.Errorf("查询数据发送错误2:%v", err)
		pagedList.Code = ERROR
		pagedList.Msg = fmt.Sprintf("数据查询错误： %s", err)
		return pagedList
	}
	for rows.Next() {
		//todo format data（格式化数据）
		rows.Scan(dest...)
		pagedList.Data = append(pagedList.Data, dest)
	}
	rows, err = DB.Query(countClause)
	if rows.Next() {
		rows.Scan(&pagedList.Count)
	} else {
		pagedList.Count = 0
	}
	return pagedList
}
